package ua.edu.nuos.tees.jdmmon;

import jssc.SerialPortException;
import ua.edu.nuos.tees.jdmmon.bl.MultimeterService;
import ua.edu.nuos.tees.jdmmon.dao.exceptions.ConfigException;
import ua.edu.nuos.tees.jdmmon.gui.GUI;
import ua.edu.nuos.tees.jdmmon.threads.DataUpdater;
import ua.edu.nuos.tees.jdmmon.threads.UpdateGuiTask;
import utils.ConfigUtils;
import vo.Config;
import vo.PATHS;

import java.io.IOException;
import java.util.Timer;
import java.util.prefs.BackingStoreException;

/**
 * Application main class
 *
 * @author Timur Yarosh
 * @author Olha Mudrievska
 *         23.02.13
 */
public class Main {

    private static Config rs232Config;
    private static Config modbusConfig;
    private static Config deviceConfig;

    public static void main(String args[]) throws IOException, SerialPortException, ConfigException,
            exceptions.ConfigException, BackingStoreException {

        if(!ConfigUtils.checkConfigs(new String[]{PATHS.COM_CONFIG})) {
            GUI.createConnectionDialog(false);
        }

        if(!ConfigUtils.checkConfigs(new String[]{PATHS.MODBUS_PROPERTIES})) {
            GUI.createSettingsDialog(false);
        }

//        if(!ConfigUtils.checkConfigs(new String[]{PATHS.DEVICES_PATH})) {
//            GUI.createLoadDeviceConfigDialog();
//        }

        rs232Config = ConfigUtils.loadConfig(
                PATHS.COM_CONFIG
        );
        modbusConfig = ConfigUtils.loadConfig(
                PATHS.MODBUS_PROPERTIES
        );
        deviceConfig = ConfigUtils.loadConfig(
                new Main().getClass().getResourceAsStream("/devices/lovato_dmk3.ini"),
                PATHS.DEVICES_PATH
        );

        try {
            MultimeterService multimeterService = new MultimeterService(
                    rs232Config,
                    modbusConfig,
                    deviceConfig,
                    true);

            GUI gui = new GUI(multimeterService);

            Timer refreshTimer = new Timer("refresh");
            refreshTimer.schedule(new UpdateGuiTask(gui), 0, 1000);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ConfigException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SerialPortException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
